#! /usr/bin/env python3
# This script fixes newlines around namespace blocks in src folder and subdirectories

import re
import sys


def processFile(filecontent):
    filecontent = re.sub(r'(    }\n)\n( *}\n)', r'\1\2', filecontent, 0, re.MULTILINE)  # remove empty lines between '}' and '}'
    filecontent = re.sub(r'(\n +class( INET_API)? \w+( : public \w+(::\w+)*)?)\n +\{', r'\1 {', filecontent, 0, re.MULTILINE)  # remove \n from inner class declarations
    filecontent = re.sub(r'(\n +class( INET_API)? \w+( : public \w+(::\w+)*)?)( //[^\n])\n +\{', r'\1 {\5', filecontent, 0, re.MULTILINE)  # remove \n from inner class declarations
    return filecontent


# configuration parameters
filelist = open(sys.argv[1], 'r')

for line in filelist:
    fullpath = line.rstrip('\n\r')
    if fullpath.endswith(('.h', '.cc')):
        print("Postprocess", fullpath)
        f = open(fullpath, 'r')
        content = f.read()
        f.close()
        newContent = processFile(content)
        if newContent != content:
            f2 = open(fullpath, 'w')
            f2.write(newContent)
            f2.close()
            print("---Updated", fullpath)
